package com.ruoyi.common.plugins;

import com.ruoyi.framework.datasource.DataSourceUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * mysql语法转化sqlite语法
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Component
public class MysqlToSqliteFunctionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        String dbType = DataSourceUtils.getDbType();

        // 使用SQLite数据库函数转换，如果不是SQLite数据库则直接返回
        if (!StringUtils.equals(DataSourceUtils.SQLITE,dbType)) {
            return invocation.proceed();
        }

        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        // 获取 BoundSql 对象
        Object boundSql = statementHandler.getBoundSql();

        // 通过反射获取 BoundSql 中的 sql 字段
        Field field = boundSql.getClass().getDeclaredField("sql");
        field.setAccessible(true);

        // 获取原始 SQL
        String originalSql = (String) field.get(boundSql);

        // 判断 SQL 类型
        String sqlType = getSqlType(originalSql);

        // 修改后的SQL
        String modifiedSql = "";

        switch (sqlType) {

            case "SELECT":

                // 替换 MySQL 的函数为 SQLite 的对应函数
                modifiedSql = replaceMysqlFunctions(originalSql);

                // 修改 SQL 字段值
                field.set(boundSql, modifiedSql);
                break;
            case "INSERT":
            case "UPDATE":
                originalSql = replaceMysqlFunctions(originalSql);

                // 使用 MetaObject 获取 SQL 参数
                MetaObject metaObject = SystemMetaObject.forObject(boundSql);

                modifiedSql = modifyUpdateSql(originalSql, statementHandler, metaObject);
                // 修改后的 SQL
                field.set(boundSql, modifiedSql);
                break;
            case "DELETE":
                modifiedSql = modifyDeleteSql(originalSql);
                // 修改后的 SQL
                field.set(boundSql, modifiedSql);
                break;
            default:

                break;
        }

        return invocation.proceed();
    }

    private String modifyDeleteSql(String sql) {
        // 使用正则表达式替换 TRUNCATE TABLE 为 DELETE FROM
        String regexTruncate = "(?i)truncate\\s+table\\s+([\\w\\d_]+)"; // 匹配 TRUNCATE TABLE 后的表名
        Pattern patternTruncate = Pattern.compile(regexTruncate);
        Matcher matcherTruncate = patternTruncate.matcher(sql);

        while (matcherTruncate.find()) {
            String original = matcherTruncate.group(0);  // 原始 TRUNCATE 语句
            String tableName = matcherTruncate.group(1); // 表名
            // 替换成 DELETE FROM
            String replacement = "";
            String delTable = "DELETE FROM " + tableName;
            if (StringUtils.equals(tableName, "sys_oper_log")) {
                replacement = delTable + " WHERE oper_id is not null";
            } else if (StringUtils.equals(tableName, "sys_logininfor")) {
                replacement = delTable + " WHERE info_id is not null";
            } else {
                replacement = delTable + " WHERE id is not null";
            }
            sql = sql.replace(original, replacement);
        }

        return sql;
    }

    /**
     * select sql
     *
     * @param sql 原sql
     * @return sql 返回替换后的sql
     */
    private String replaceMysqlFunctions(String sql) {

        // 替换 LEFT(m.money_date, 7) 为 strftime('%Y-%m', m.money_date)
        sql = sql.replaceAll("(?i)LEFT\\(([^,]+),\\s*7\\)", "strftime('%Y-%m', $1)");

        //  替换 if 函数为 CASE WHEN ：例如 if(ac.status = 1, am.money, 0) 替换为  CASE WHEN ac.status = 1 THEN am.money ELSE 0 END
        sql = sql.replaceAll("if\\(([^,]+?),\\s*([^,]+?),\\s*([^,]+?)\\)", "CASE WHEN $1 THEN $2 ELSE $3 END");

        //  替换 DATE_FORMAT 为 strftime
        sql = sql.replaceAll("DATE_FORMAT\\(([^,]+?),\\s*'%Y-%m'\\)", "strftime('%Y-%m', $1)");

        //  替换 ) - INTERVAL n.number MONTH 为 ), '-' || n.number || ' month'
        sql = sql.replaceAll("\\)\\s*-\\s*INTERVAL\\s+n\\.number\\s+MONTH", "), '-' || n.number || ' month'");

        // 替换 WEEKDAY(m.money_date) 为 strftime('%w', m.money_date)
        sql = sql.replaceAll("weekday\\(([^)]+)\\)", "strftime('%w', $1)");

        // 替换 IFNULL(expr || '') 为 IFNULL(expr, '') 案例：用户管理-编辑-菜单管理
        String regexIfnull = "(?i)\\bIFNULL\\s*\\(\\s*(.+?)\\s*\\|\\|\\s*''\\s*\\)";
        Pattern patternRegexIfnull = Pattern.compile(regexIfnull);
        Matcher matcherRegexIfnull = patternRegexIfnull.matcher(sql);
        while (matcherRegexIfnull.find()) {
            sql = sql.replaceAll(regexIfnull, "IFNULL($1, '')");
        }

        /**
         *  SELECT
         *  	GROUP_CONCAT(
         *  		DISTINCT CONCAT( 'sum(IF(c.id = ''', c.id, ''',  m.money, 0)) AS ', concat( '\'', concat( c.id, '\'' )) )
         *  	ORDER BY
         *  		c.STATUS,
         *  		c.order_num
         *  	)
         *  FROM
         *  	account_class c 将 mysql 语法返回 sqlite 语法
         *  SELECT
         * 	    GROUP_CONCAT( DISTINCT 'sum(IF(c.id = ''' || c.id || ''', m.money, 0)) AS ' || '''' || c.id || '''' ORDER BY c.status, c.order_num )
         *  FROM
         * 	account_class c;
         */
        // 定义正则表达式来匹配 GROUP_CONCAT(DISTINCT CONCAT(...))
        Pattern groupConcatPattern = Pattern.compile("GROUP_CONCAT.*DISTINCT.*CONCAT.*account_class", Pattern.DOTALL);
        Matcher groupConcatMatcher = groupConcatPattern.matcher(sql);
        if (groupConcatMatcher.find()) {
            return sql = "SELECT\n" +
                    "    GROUP_CONCAT(\n" +
                    "        DISTINCT 'sum(IF(c.id = ''' || c.id || ''', m.money, 0)) AS ''' || c.id || ''''\n" +
                    "    )\n" +
                    "FROM\n" +
                    "    account_class c\n" +
                    "ORDER BY\n" +
                    "    c.status, c.order_num;";
        }

        // 定义正则表达式来匹配原始的 CONCAT 表达式
        String blogImgConcat = "CONCAT\\s*\\(\\s*'(/blog/img/)'\\s*,\\s*" + // 匹配 '/blog/img/' 部分
                "\\(\\s*SELECT\\s+FLOOR\\s*\\(\\s*RAND\\(\\)\\s*\\*\\s*22\\s*\\)\\s*\\)\\s*" + // 匹配 RAND() 和乘法
                ",\\s*'(\\.jpg)'\\s*\\)";
        Pattern patternBlogImgConcat = Pattern.compile(blogImgConcat);
        Matcher matcherBlogImgConcat = patternBlogImgConcat.matcher(sql);
        while (matcherBlogImgConcat.find()) {
            String original = matcherBlogImgConcat.group(0);
            String replacement = "'/blog/img/' || CAST(ABS(RANDOM()) % 22 AS TEXT) || '.jpg'";
            sql = sql.replace(matcherBlogImgConcat.group(0), replacement);
        }


        // 替换 CONCAT() 函数为 SQLite 的字符串连接符 ||
        String regexConcat = "(?i)CONCAT\\((.*?)\\)";
        Pattern patternConcat = Pattern.compile(regexConcat);
        Matcher matcherConcat = patternConcat.matcher(sql);
        while (matcherConcat.find()) {
            String original = matcherConcat.group(0);
            String params = matcherConcat.group(1);
            // SQLite 使用 || 来连接字符串
            String replacement = params.replaceAll(",\\s*", " || ");
            sql = sql.replace(original, replacement);
        }

        // 替换 DATE_FORMAT() 函数为 SQLite 的 strftime() 函数
        String regexDateFormat = "(?i)DATE_FORMAT\\((.*?),\\s*'(.*?)'\\)";
        Pattern patternDateFormat = Pattern.compile(regexDateFormat);
        Matcher matcherDateFormat = patternDateFormat.matcher(sql);
        while (matcherDateFormat.find()) {
            String original = matcherDateFormat.group(0);
            String dateField = matcherDateFormat.group(1);
            String format = matcherDateFormat.group(2);
            // SQLite 使用 strftime() 来格式化日期
            String replacement = "strftime('" + format + "', " + dateField + ")";
            sql = sql.replace(original, replacement);
        }

        // 替换 IFNULL() 函数为 SQLite 的 COALESCE()
        String regexIfNull = "(?i)IFNULL\\((.*?),\\s*(.*?)\\)";
        Pattern patternIfNull = Pattern.compile(regexIfNull);
        Matcher matcherIfNull = patternIfNull.matcher(sql);
        while (matcherIfNull.find()) {
            String original = matcherIfNull.group(0);
            String expr1 = matcherIfNull.group(1);
            String expr2 = matcherIfNull.group(2);
            // SQLite 使用 COALESCE() 来替代 IFNULL()
            String replacement = "COALESCE(" + expr1 + ", " + expr2 + ")";
            sql = sql.replace(original, replacement);
        }

        // 替换 NOW() 为 CURRENT_TIMESTAMP
        String regexNow = "(?i)NOW\\(\\)";
        Pattern patternNow = Pattern.compile(regexNow);
        Matcher matcherNow = patternNow.matcher(sql);
        while (matcherNow.find()) {
            String original = matcherNow.group(0);
            // SQLite 使用 CURRENT_TIMESTAMP
            String replacement = "CURRENT_TIMESTAMP";
            sql = sql.replace(original, replacement);
        }

        // 替换 CURDATE() 为 DATE('now')
        String regexCurdate = "(?i)CURDATE\\(\\)";
        Pattern patternCurdate = Pattern.compile(regexCurdate);
        Matcher matcherCurdate = patternCurdate.matcher(sql);
        while (matcherCurdate.find()) {
            String original = matcherCurdate.group(0);
            // SQLite 使用 DATE('now')
            String replacement = "DATE('now')";
            sql = sql.replace(original, replacement);
        }

        // 替换 UUID() 为 SQLite 的方法
        String regexUuid = "(?i)UUID\\(\\)";
        Pattern patternUuid = Pattern.compile(regexUuid);
        Matcher matcherUuid = patternUuid.matcher(sql);
        while (matcherUuid.find()) {
            String original = matcherUuid.group(0);
            // SQLite 通过 `lower(hex(randomblob(16)))` 获取 UUID
            String replacement = "lower(hex(randomblob(16)))";
            sql = sql.replace(original, replacement);
        }

        // 替换 sysdate() 为 DATETIME('now')
        String regexSysdate = "(?i)SYSDATE\\(\\)";
        Pattern patternSysdate = Pattern.compile(regexSysdate);
        Matcher matcherSysdate = patternSysdate.matcher(sql);
        while (matcherSysdate.find()) {
            String original = matcherSysdate.group(0);
            // SQLite 使用 DATETIME('now') 来替代 sysdate()
            String replacement = "DATETIME('now','localtime')";
            sql = sql.replace(original, replacement);
        }

        // 替换 UNIX_TIMESTAMP() 为 SQLite 的 strftime() 函数
        String regexUnixTimestamp = "(?i)UNIX_TIMESTAMP\\(\\)";
        Pattern patternUnixTimestamp = Pattern.compile(regexUnixTimestamp);
        Matcher matcherUnixTimestamp = patternUnixTimestamp.matcher(sql);
        while (matcherUnixTimestamp.find()) {
            String original = matcherUnixTimestamp.group(0);
            // SQLite 使用 strftime('%s', 'now') 来获取当前的 Unix 时间戳
            String replacement = "strftime('%s', 'now')";
            sql = sql.replace(original, replacement);
        }

        // 替换 FROM_UNIXTIME() 为 SQLite 的 strftime() 函数
        String regexFromUnixTime = "(?i)FROM_UNIXTIME\\((.*?)\\)";
        Pattern patternFromUnixTime = Pattern.compile(regexFromUnixTime);
        Matcher matcherFromUnixTime = patternFromUnixTime.matcher(sql);
        while (matcherFromUnixTime.find()) {
            String original = matcherFromUnixTime.group(0);
            String timestamp = matcherFromUnixTime.group(1);
            // SQLite 使用 strftime() 来转换 Unix 时间戳为日期
            String replacement = "strftime('%Y-%m-%d %H:%M:%S', " + timestamp + ", 'unixepoch')";
            sql = sql.replace(original, replacement);
        }

        // 替换 IF() 函数为 SQLite 的 CASE WHEN
        String regexIf = "(?i)IF\\((.*?),\\s*(.*?),\\s*(.*?)\\)";
        Pattern patternIf = Pattern.compile(regexIf);
        Matcher matcherIf = patternIf.matcher(sql);
        while (matcherIf.find()) {
            String original = matcherIf.group(0);
            String condition = matcherIf.group(1);
            String trueValue = matcherIf.group(2);
            String falseValue = matcherIf.group(3);
            // SQLite 使用 CASE WHEN 来替代 IF
            String replacement = "CASE WHEN " + condition + " THEN " + trueValue + " ELSE " + falseValue + " END";
            sql = sql.replace(original, replacement);
        }

        // 替换 MySQL 的 REPLACE INTO 为 SQLite 的 INSERT INTO ... ON CONFLICT REPLACE
        String regexReplace = "(?i)REPLACE INTO";
        Pattern patternReplace = Pattern.compile(regexReplace);
        Matcher matcherReplace = patternReplace.matcher(sql);
        while (matcherReplace.find()) {
            if (!StringUtils.containsIgnoreCase(sql, "INSERT OR REPLACE INTO")) {
                String original = matcherReplace.group(0);
                // SQLite 使用 INSERT INTO ... ON CONFLICT REPLACE
                String replacement = "INSERT INTO";
                sql = sql.replace(original, replacement);
            }
        }

        // 替换 ISNULL() 为 SQLite 的 IFNULL()
        String regexIsNull = "(?i)ISNULL\\((.*?)\\)";
        Pattern patternIsNull = Pattern.compile(regexIsNull);
        Matcher matcherIsNull = patternIsNull.matcher(sql);
        while (matcherIsNull.find()) {
            String original = matcherIsNull.group(0);
            String param = matcherIsNull.group(1);
            // SQLite 使用 IFNULL 来代替 ISNULL
            String replacement = "IFNULL(" + param + ", '')";  // 可以根据需求将空字符串替换为其他默认值
            sql = sql.replace(original, replacement);
        }

        // 替换 LENGTH() 为 SQLite 的 LENGTH()
        String regexLength = "(?i)LENGTH\\((.*?)\\)";
        Pattern patternLength = Pattern.compile(regexLength);
        Matcher matcherLength = patternLength.matcher(sql);
        while (matcherLength.find()) {
            String original = matcherLength.group(0);
            String param = matcherLength.group(1);
            // SQLite 使用 LENGTH() 直接不需要更改
            String replacement = "LENGTH(" + param + ")";
            sql = sql.replace(original, replacement);
        }

        // 替换 TRIM() 为 SQLite 的 TRIM()
        String regexTrim = "(?i)TRIM\\((.*?)\\)";
        Pattern patternTrim = Pattern.compile(regexTrim);
        Matcher matcherTrim = patternTrim.matcher(sql);
        while (matcherTrim.find()) {
            String original = matcherTrim.group(0);
            String param = matcherTrim.group(1);
            // SQLite 使用 TRIM() 不需要修改
            String replacement = "TRIM(" + param + ")";
            sql = sql.replace(original, replacement);
        }

        // 替换 RAND() 为 SQLite 的 RANDOM()
        String regexRand = "(?i)RAND\\((.*?)\\)";
        Pattern patternRand = Pattern.compile(regexRand);
        Matcher matcherRand = patternRand.matcher(sql);
        while (matcherRand.find()) {
            String original = matcherRand.group(0);
            String replacement = "RANDOM()";
            sql = sql.replace(original, replacement);
        }

        // 替换 MySQL 的 REPLACE INTO 为 SQLite 的 INSERT OR REPLACE INTO
        String regexReplaceInto = "(?i)REPLACE\\s+INTO";
        Pattern patternReplaceInto = Pattern.compile(regexReplaceInto);
        Matcher matcherReplaceInto = patternReplaceInto.matcher(sql);
        while (matcherReplaceInto.find()) {
            if (!StringUtils.containsIgnoreCase(sql, "INSERT OR REPLACE INTO")) {
                sql = matcherReplaceInto.replaceAll("INSERT OR REPLACE INTO");
            }
        }

        String regexFindInSet = "(?i)FIND_IN_SET\\((.*?),\\s*(.*?)\\)";
        Pattern patternFindInSet = Pattern.compile(regexFindInSet);
        Matcher matcherFindInSet = patternFindInSet.matcher(sql);
        while (matcherFindInSet.find()) {
            // 使用 StringBuffer 来构建新的 SQL 语句
            StringBuffer newSql = new StringBuffer();
            String original = matcherFindInSet.group(0);
            String valuePlaceholder = matcherFindInSet.group(1);  // 查找的值的占位符
            String ancestors = matcherFindInSet.group(2);  // 要匹配的字段 (ancestors)

            // 使用占位符 ? 替代直接插入 value
            String replacement = "(',' || " + ancestors + " || ',') LIKE '%,' || ? || ',%'";
            matcherFindInSet.appendReplacement(newSql, Matcher.quoteReplacement(replacement));
            matcherFindInSet.appendTail(newSql);
            sql = newSql.toString();
        }


        // 你可以继续在此处添加更多的 MySQL 函数的替换...

        return sql;
    }

    /**
     * update/insert sql
     *
     * @param sql        原sql
     * @param metaObject 参数
     * @return sql 返回替换后的sql
     */
    private String modifyUpdateSql(String sql, StatementHandler statementHandler, MetaObject metaObject) throws NoSuchFieldException, IllegalAccessException {

        // 获取 SQL 参数对象，通常是一个对象数组（Object[]）
        Object parameterObject = metaObject.getValue("parameterObject");

        // 检查 parameterObject 是否是 AccountMoney 实体类
        if (parameterObject != null) {

            // 检查 parameterObject 是否为 Map 类型或包含 param1 和 et 字段
//            if (parameterObject instanceof Map) {
//                Map<String, Object> paramMap = (Map<String, Object>) parameterObject;
//
//                // 获取 param1 和 et 字段的值
//                Object param1 = paramMap.get("param1");
//                Object et = paramMap.get("et");
//
//                // 获取 updateTime 字段值
//                Object dateTimeValue = null;
//                if (param1 != null) {
//                    dateTimeValue = getUpdateTimeFromObject(param1);
//                }
//                if (dateTimeValue == null && et != null) {
//                    dateTimeValue = getUpdateTimeFromObject(et);
//                }
//                if (dateTimeValue != null) {
//                    // 如果 updateTime 为 Date 类型
//                    if (dateTimeValue instanceof Date) {
//                        Date updateTime = (Date) dateTimeValue;
//                        // 将 updateTime 转换为 SQLite 支持的时间格式
//                        String formattedDate = "strftime('%Y-%m-%d %H:%M:%S', '" + updateTime.getTime() + "' / 1000, 'unixepoch')";
//
//                        // 使用正则表达式匹配 SQL 中的 ? 占位符，替换为 formattedDate
//                        String regexUpdateTime = "(update_time\\s*=\\s*)\\?";
//                        Pattern patternUpdateTime = Pattern.compile(regexUpdateTime);
//                        Matcher matcherUpdateTime = patternUpdateTime.matcher(sql);
//                        if (matcherUpdateTime.find()) {
//                            // 替换 SQL 中的占位符 将 ? 替换为 formattedDate
//                            sql = sql.replace("update_time=?", "update_time=?, update_time=" + formattedDate);
//                        }
//                    }
//                }
//            }

            // 正则表达式匹配 "money_date = ?" 来查找 SQL 中的 money_date 字段
            String regex = "(money_date\\s*=\\s*)\\?";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(sql);

            if (matcher.find()) {

                // 获取 AccountMoney 类中的 money_date 字段
                Field moneyDateField = parameterObject.getClass().getDeclaredField("moneyDate");
                moneyDateField.setAccessible(true);  // 让私有字段可访问

                Object moneyDateValue = moneyDateField.get(parameterObject);

                // 如果 money_date 是时间戳（Long 类型）
                if (moneyDateValue instanceof Date) {
                    Long timestamp = ((Date) moneyDateValue).getTime();

                    // 将时间戳转换为 strftime 格式
                    String formattedDate = "strftime('%Y-%m-%d', '" + timestamp + "' / 1000, 'unixepoch')";

                    if (matcher.find()) {
                        // 替换 SQL 中的 "money_date = ?" 为转换后的 strftime 格式
                        sql = sql.replaceFirst("\\?", formattedDate);
                    }
                }
            }
        }

        // 正则表达式：匹配 MySQL 的 INSERT INTO ... ON DUPLICATE KEY UPDATE
        String regexOnUpdate = "(?i)insert\\s+into\\s+([a-zA-Z0-9_]+)\\s*\\((.*?)\\)\\s*values\\s*((?:\\(.*?\\)\\s*,?\\s*)+)(on\\s+duplicate\\s+key\\s+update\\s*.*)?";
        Pattern patternOnUpdate = Pattern.compile(regexOnUpdate);
        Matcher matcherOnUpdate = patternOnUpdate.matcher(sql);
        while (matcherOnUpdate.find()) {
            if (StringUtils.containsIgnoreCase(sql, "DUPLICATE")) {

                String tableName = matcherOnUpdate.group(1);  // 表名
                String columns = matcherOnUpdate.group(2);   // 列名
                String values = matcherOnUpdate.group(3);    // 值

                // 处理 SQL 语句：合并所有的 VALUES 为一个大列表
                return sql = "INSERT OR REPLACE INTO " + tableName +
                        " (" + columns + ") " +
                        "VALUES " + values + ";";

            }
        }

        // 正则表达式：匹配 REPLACE INTO（忽略大小写）
        String regexReplaceInto = "(?i)replace\\s+into";
        Pattern patternReplaceInto = Pattern.compile(regexReplaceInto);
        Matcher matcherReplaceInto = patternReplaceInto.matcher(sql);
        // 在匹配到 REPLACE INTO 时进行替换
        while (matcherReplaceInto.find()) {
            if (!StringUtils.containsIgnoreCase(sql, "INSERT OR REPLACE INTO")) {
                String original = matcherReplaceInto.group(0);
                String replacement = "INSERT OR REPLACE INTO";  // 替换内容
                return sql = sql.replace(original, replacement);
            }
        }

        // 替换 ON CONFLICT(sessionId) REPLACE
//        String regexConflictReplace = "(?i)INSERT INTO(.*)VALUES(.*)";
//        Pattern patternConflictReplace = Pattern.compile(regexConflictReplace);
//        Matcher matcherConflictReplace = patternConflictReplace.matcher(sql);
//        while (matcherConflictReplace.find()) {
//            String original = matcherConflictReplace.group(0);
//            String replacement = original + " ON CONFLICT(sessionId) REPLACE";
//            return sql = sql.replace(original, replacement);
//        }

        // 替换 MySQL 的 REPLACE INTO 为 SQLite 的 INSERT INTO ... ON CONFLICT ... DO UPDATE
        String regexReplaceIntoTable = "(?i)REPLACE INTO\\s+(\\w+)\\s*\\((.*?)\\)\\s*VALUES\\s*\\((.*?)\\)";
        Pattern patternReplaceIntoTable = Pattern.compile(regexReplaceIntoTable);
        Matcher matcherReplaceIntoTable = patternReplaceIntoTable.matcher(sql);
        while (matcherReplaceIntoTable.find()) {
            if (!StringUtils.containsIgnoreCase(sql, "INSERT OR REPLACE INTO")) {
                String original = matcherReplaceIntoTable.group(0);
                String table = matcherReplaceIntoTable.group(1);  // 表名
                String columns = matcherReplaceIntoTable.group(2); // 列名
                String values = matcherReplaceIntoTable.group(3);  // 值

                // 获取第一个列（假设它是冲突的主键列）
                String[] columnArray = columns.split(",");
                String conflictColumn = columnArray[0].trim();

                // 构造替换后的 SQL
                String replacement = "INSERT INTO " + table + " (" + columns + ") "
                        + "VALUES (" + values + ") "
                        + "ON CONFLICT(" + conflictColumn + ") "
                        + "DO UPDATE SET "
                        + conflictColumn + " = excluded." + conflictColumn;

                return sql = sql.replace(original, replacement);
            }
        }

        return sql;
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 这里可以配置插件的属性，如果需要
    }

    // 获取 SQL 类型的方法
    private String getSqlType(String sql) {
        // 去掉多余的空格和换行符，转换成大写进行判断
        String trimmedSql = sql.trim().toUpperCase();
        if (trimmedSql.startsWith("INSERT")) {
            return "INSERT";
        } else if (trimmedSql.startsWith("UPDATE")) {
            return "UPDATE";
        } else if (trimmedSql.startsWith("DELETE")) {
            return "DELETE";
        } else if (trimmedSql.startsWith("SELECT")) {
            return "SELECT";
        } else if (trimmedSql.startsWith("TRUNCATE")) {
            return "DELETE";
        }
        return "UNKNOWN";
    }

    private Object getUpdateTimeFromObject(Object object) throws NoSuchFieldException, IllegalAccessException {
        if (object != null) {
            // 获取对象的 Class 类型
            Class<?> clazz = object.getClass();

            // 使用反射获取 updateTime 字段
            Field updateTimeField = clazz.getDeclaredField("updateTime");
            updateTimeField.setAccessible(true); // 使私有字段可访问
            Object o = updateTimeField.get(object);
            updateTimeField.set(object, null);   // 设置为 null

            // 获取字段值
            return o;
        }
        return null;
    }

}
